var TimerObject = function(){
	this.next_tid = 0;
	this.timers = [];
};

TimerObject.prototype.setTimeout = function(cb, timeout){
	var nid = this.next_tid++;
	var now = os.gettimeofday();
	var usec = now.usec + timeout*1000;
	var next = {};
	next.sec = Math.floor(now.sec + usec/1000000);
	next.usec = usec%1000000;

	//console.log("setTimeout:now-" + now.sec + "/" + now.usec + ", next-" + next.sec + "/" + next.usec);
	this.timers.push({tid:nid, cb:cb, type:0, timeout:timeout, timeover:next, count:0});

	//console.log("timers count=" + this.timers.length);

	return nid;
};

TimerObject.prototype.clearTimeout = function(nid)
{
	var id;
	for(var i=0; i<this.timers.length; i++){
		if(this.timers[i].tid == nid){
			this.timers.splice(i, 1);
			return true;
		}
	}
	return false;
};

TimerObject.prototype.setInterval = function(cb, timeinterval){
	var nid = this.next_tid ++;
	var now = os.gettimeofday();
	var usec = now.usec + timeinterval*1000;
	var next = {};
	next.sec = Math.floor(now.sec + usec/1000000);
	next.usec = usec%1000000;

	//console.log("setInterval:now-" + now.sec + "/" + now.usec + ", next-" + next.sec + "/" + next.usec);

	this.timers.push({tid:nid, cb:cb, type:1, timeout:timeinterval, timeover:next, count:0});

	//console.log("timers count=" + this.timers.length);

	return nid;
};

TimerObject.prototype.clearInterval = function(nid)
{
	return this.clearTimeout(nid);
};


TimerObject.prototype.timeoutCheck = function()
{
	var repeat = false;

	do{
	 
		var now = os.gettimeofday();
		var len = this.timers.length;
		repeat = false;

		for(var i=0; i<len; i++)
		{
			var timer = this.timers[i];
			if(now.sec > timer.timeover.sec || (now.sec == timer.timeover.sec && now.usec >= timer.timeover.usec))
			{
				 //console.log("Found timeout, cb is " + typeof timer.cb);
				
				if(typeof timer.cb == 'function')
					timer.cb();
				else
					os.eval_string(timer.cb);

				if(timer.type == 1){	
					var next = {};
					var usec = now.usec + timer.timeout*1000;
					next.sec = Math.floor(now.sec + usec/1000000);
					next.usec = usec%1000000;
					timer.timeover = next;
					timer.count ++;
				}
				else
				{
					this.timers.splice(i, 1);
					if(i != (len-1))
						repeat = true;
					break;
				}
			}
			else{
			}
		}
	}while(repeat);
};

var gto = new TimerObject();
function setTimeout(cb, timeout){ return gto.setTimeout(cb, timeout); }
function setInterval(cb, timeout){ return gto.setInterval(cb, timeout); }
function clearTimeout(nid){ return gto.clearTimeout(nid);}
function clearInterval(nid){ return gto.clearInterval(nid);}
function timeoutCheck(){return gto.timeoutCheck();}

module.exports = gto;
